package com.sayice.robotconflict.view.page

import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import com.sayice.robotconflict.ui.screen.cdp
import com.sayice.robotconflict.viewmodel.GameViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 登录页面
 */
@Composable
fun Login(viewModel: GameViewModel) {
    val scope = rememberCoroutineScope()
    var name by rememberSaveable { mutableStateOf("") }
    var password by rememberSaveable { mutableStateOf("") }
    Box(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier.align(Alignment.Center),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text("玩家名:")
                TextField(
                    value = name,
                    onValueChange = { name = it },
                    modifier = Modifier.padding(10.cdp)
                )
            }
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(" 密 码: ")
                TextField(
                    value = password,
                    onValueChange = { password = it },
                    modifier = Modifier.padding(10.cdp)
                )
            }
            Row(
                horizontalArrangement = Arrangement.SpaceAround,
                modifier = Modifier.width(500.cdp)
            ) {
                Button(onClick = {
                    scope.launch(Dispatchers.IO) {
                        viewModel.register(name, password)
                    }
                }) {
                    Text(
                        text = "注册",
                        textAlign = TextAlign.Center
                    )
                }
                Button(onClick = {
                    scope.launch(Dispatchers.IO) {
                        viewModel.login(name, password)
                    }
                }) {
                    Text(
                        text = "登录",
                        textAlign = TextAlign.Center
                    )
                }
            }
        }
    }
}